package org.jeecg.modules.demo.sendEmail.service;

import com.sun.mail.util.MailSSLSocketFactory;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Component
public class MailPushService {

    private final Logger LOGGER = LoggerFactory.getLogger(MailPushService.class);

    @Value(value = "${spring.mail.host}")
    private String host;

    @Value(value = "${spring.mail.port}")
    private String port;

    @Value(value = "${spring.mail.protocol}")
    private String protocol;

    @Value(value = "${spring.mail.username}")
    private String username;

    @Value(value = "${spring.mail.password}")
    private String password;

    @Value(value = "${spring.mail.fromEmail}")
    private String fromEmail;

    @Value(value = "${spring.mail.fromPersonal}")
    private String fromPersonal;



    public static String buildHtmlContent(String userName) throws Exception {
        // 配置 FreeMarker
        Configuration configuration = new Configuration(new Version("2.3.31"));
        configuration.setDefaultEncoding(Charset.forName("UTF-8").name());
        configuration.setClassForTemplateLoading(MailPushService.class, "/templates");

        // 获取模板
        Template template = configuration.getTemplate("demo.ft1");

        // 动态变量替换
        Map<String, Object> map = new HashMap<>();
        map.put("userName", userName);
        String htmlstr= FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        // 渲染模板为字符串
        return htmlstr;
    }

    /**
     * 发送邮件（单个发送）
     * @param toEmail    接受者邮箱
     * @param subject    主题
     * @param Content   内容
     * @param attachment 附件
     */
    public void sendMail(String toEmail, String subject, String Content, MultipartFile attachment) {
        try {
            // 设置了附件名过长问题
            System.setProperty("mail.mime.splitlongparameters", "false");
            final Properties props = new Properties();
            // 服务器
            props.put("mail.smtp.host", host);
            // 端口
            props.put("mail.smtp.port", port);
            // 协议
            props.setProperty("mail.transport.protocol", protocol);
            // 用户名
            props.put("mail.user", username);
            // 密码
            props.put("mail.password", password);
            // 使用smtp身份验证
            props.put("mail.smtp.auth", "true");

            // 开启安全协议
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(props.getProperty("mail.user"),
                            props.getProperty("mail.password"));
                }
            };

            Session session = Session.getDefaultInstance(props, authenticator);
            session.setDebug(true);
            MimeMessage mimeMessage = new MimeMessage(session);
            // 发送者邮箱
            mimeMessage.setFrom(new InternetAddress(fromEmail, MimeUtility.encodeText(fromPersonal)));
            // 接受者邮箱
            mimeMessage.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toEmail));
            // 邮件主题
            mimeMessage.setSubject(subject);
            // 定义邮件内容
            Multipart multipart = new MimeMultipart();

            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(Content, "text/plain;charset=UTF-8"); // 改为 text/plain
            multipart.addBodyPart(contentPart);

            // 添加附件
            if (attachment != null && !attachment.isEmpty()) { // 确保附件不为空
                try (InputStream inputStream = attachment.getInputStream()) { // 使用 try-with-resources 自动关闭流
                    BodyPart attachmentBodyPart = new MimeBodyPart();

                    // 使用 MultipartFile 的 InputStream 作为数据源
                    DataSource fds = new ByteArrayDataSource(inputStream, attachment.getContentType());

                    attachmentBodyPart.setDataHandler(new DataHandler(fds));

                    // 设置文件名，避免乱码
                    attachmentBodyPart.setFileName(MimeUtility.encodeText(attachment.getOriginalFilename()));

                    multipart.addBodyPart(attachmentBodyPart);
                } catch (IOException e) {
                    LOGGER.error("处理附件时发生异常！", e);
                    throw e; // 抛出异常，确保外部捕获
                }
            }

            // 将multipart对象放到message中
            mimeMessage.setContent(multipart);

            // 保存信息
            mimeMessage.saveChanges();
            // 发送消息
            Transport.send(mimeMessage);
            LOGGER.info("邮件已经发送。");
        } catch (Exception e) {
            LOGGER.error("发送邮件时发生异常！", e);
        }
    }

    /**
     * 发送邮件（给多人发送）
     * @param toEmails    接受者邮箱
     * @param subject    主题
     * @param Content   内容
     * @param attachment 附件
     */
    public void sendMail(String[] toEmails, String subject, String Content, MultipartFile attachment) {
        try {
            // 设置了附件名过长问题
            System.setProperty("mail.mime.splitlongparameters", "false");
            final Properties props = new Properties();
            // 服务器
            props.put("mail.smtp.host", host);
            // 端口
            props.put("mail.smtp.port", port);
            // 协议
            props.setProperty("mail.transport.protocol", protocol);
            // 用户名
            props.put("mail.user", username);
            // 密码
            props.put("mail.password", password);
            // 使用smtp身份验证
            props.put("mail.smtp.auth", "true");

            // 开启安全协议
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(props.getProperty("mail.user"),
                            props.getProperty("mail.password"));
                }
            };

            Session session = Session.getDefaultInstance(props, authenticator);
            session.setDebug(true);
            MimeMessage mimeMessage = new MimeMessage(session);
            // 发送者邮箱
            mimeMessage.setFrom(new InternetAddress(fromEmail, MimeUtility.encodeText(fromPersonal)));
            // 接受者邮箱
            InternetAddress[] addresses = new InternetAddress[toEmails.length];
            for (int i = 0; i < toEmails.length; i++) {
                addresses[i] = new InternetAddress(toEmails[i]);
            }
            mimeMessage.setRecipients(MimeMessage.RecipientType.TO, addresses);
            // 邮件主题
            mimeMessage.setSubject(subject);
            // 定义邮件内容
            Multipart multipart = new MimeMultipart();

            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(Content, "text/plain;charset=UTF-8"); // 改为 text/plain
            multipart.addBodyPart(contentPart);

            // 添加附件
            if (attachment != null && !attachment.isEmpty()) { // 确保附件不为空
                try (InputStream inputStream = attachment.getInputStream()) { // 使用 try-with-resources 自动关闭流
                    BodyPart attachmentBodyPart = new MimeBodyPart();

                    // 使用 MultipartFile 的 InputStream 作为数据源
                    DataSource fds = new ByteArrayDataSource(inputStream, attachment.getContentType());

                    attachmentBodyPart.setDataHandler(new DataHandler(fds));

                    // 设置文件名，避免乱码
                    attachmentBodyPart.setFileName(MimeUtility.encodeText(attachment.getOriginalFilename()));

                    multipart.addBodyPart(attachmentBodyPart);
                } catch (IOException e) {
                    LOGGER.error("处理附件时发生异常！", e);
                    throw e; // 抛出异常，确保外部捕获
                }
            }


            // 将multipart对象放到message中
            mimeMessage.setContent(multipart);

            // 保存信息
            mimeMessage.saveChanges();
            // 发送消息
            Transport.send(mimeMessage);
            LOGGER.info("邮件已经发送。");
        } catch (Exception e) {
            LOGGER.error("发送邮件时发生异常！", e);
        }
    }


}